#include <REGX52.H>
#include "Timer0.h"
#include "Key.h"
#include "nixieTube.h"
#include "Delay.h"
#include "AT24C02.h"

unsigned char keyNum;
//unsigned char temp;
unsigned char min, sec, miniSec;
unsigned char runFlag;

void main()
{
    Timer0_Init();
    while (1)
    {
        keyNum = Key();
//        if (keyNum)
//        {
//            temp = keyNum;
//        }
//        nixieTube(1, temp);
//        Delay(100);
//        if (keyNum)
//        {
//            nixie_setbuf(1, keyNum);
//            nixie_setbuf(2, keyNum);
//            nixie_setbuf(3, keyNum);
//        }
//        Delay(1000);  // Delay仅影响响应时间
        if (keyNum == 1)
        {
            runFlag = ~runFlag;
        }
        if (keyNum == 2)
        {
            min = 0;
            sec = 0;
            miniSec = 0;
        }
        // 写入
        if (keyNum == 3)
        {
            AT24C02_writebyte(0, min);
            Delay(5);
            AT24C02_writebyte(1, sec);
            Delay(5);
            AT24C02_writebyte(2, miniSec);
            Delay(5);
        }
        // 读出
        if (keyNum == 4)
        {
            min = AT24C02_readbyte(0);
            sec = AT24C02_readbyte(1);
            miniSec = AT24C02_readbyte(2);
        }
        nixie_setbuf(1, min / 10);
        nixie_setbuf(2, min % 10);
        nixie_setbuf(3, 11);
        nixie_setbuf(4, sec / 10);
        nixie_setbuf(5, sec % 10);
        nixie_setbuf(6, 11);
        nixie_setbuf(7, miniSec / 10);
        nixie_setbuf(8, miniSec % 10);
    }
}

void sec_loop(void)
{
    if (runFlag)
    {
        miniSec++;
        if (miniSec >= 100)
        {
            miniSec = 0;
            sec++;
            if (sec >= 60)
            {
                sec = 0;
                min++;
                if (min >= 60)
                {
                    min = 0;
                }
            }
        }
    }

}

void Timer0_Rountine(void) interrupt 1
{
    static unsigned int t0_count1, t0_count2, t0_count3;
    TL0 = 0x18;     //设置定时初始值
    TH0 = 0xFC;     //设置定时初始值
    t0_count1++;
    if (t0_count1 >= 20)
    {
        t0_count1 = 0;
        Key_loop();
    }
    t0_count2++;
    if (t0_count2 >= 2)
    {
        t0_count2 = 0;
        Nixie_loop();
    }
    t0_count3++;
    if (t0_count3 >= 10)
    {
        t0_count3 = 0;
        sec_loop();
    }
}
